import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store';
import routes from './routes';

Vue.use(VueRouter);

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.meta.auth) {
    // 需要鉴权
    const status = store.getters['loginInfo/status'];
    if (status === 'checking') {
      // 加载中 进入鉴权等待页
      next({
        name: 'loading',
        query: {
          target: to.name,
        },
      });
    } else if (status === 'login') {
      // 已登录 直接进
      next();
    } else {
      // 未登录 跳转到登录页
      alert('请先登录');
      next({ name: 'login', query: { target: to.name } });
    }
  } else {
    // 不需要鉴权 直接进
    next();
  }
});

export default router;
